package com.example.networklab.mq.listener;

import com.example.networklab.constants.MQConstants;
import com.example.networklab.domain.po.StudentGrade;
import com.example.networklab.domain.po.TaskHistory;
import com.example.networklab.enums.TaskHistoryStatus;
import com.example.networklab.mq.dto.TaskScoreMQDTO;
import com.example.networklab.service.IStudentGradeService;
import com.example.networklab.service.ITaskHistoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@RequiredArgsConstructor
@Slf4j
public class TaskScoreListener {
    private final ITaskHistoryService taskHistoryService;
    private final IStudentGradeService studentGradeService;

    @RabbitListener(queuesToDeclare = @Queue(value = MQConstants.TASK_SCORE_QUEUE_NAME))
    @Transactional
    public void listenTaskScore(TaskScoreMQDTO taskScoreMQDTO) {
        log.info("收到队列名为[{}]消息:[{}]", MQConstants.TASK_SCORE_QUEUE_NAME, taskScoreMQDTO);
        TaskHistory taskHistory = taskHistoryService.getById(taskScoreMQDTO.getId());
        if (taskHistory == null) {
            log.error("队列[{}]消息处理失败:[{}]", MQConstants.TASK_SCORE_QUEUE_NAME, taskScoreMQDTO);
            return;
        }
        taskHistory.setScore(taskScoreMQDTO.getScore());
        taskHistory.setStatus(TaskHistoryStatus.CHECKED);
        taskHistoryService.updateById(taskHistory);
        // 更新最高成绩表
        StudentGrade studentGrade = studentGradeService.lambdaQuery()
                .eq(StudentGrade::getTaskId, taskHistory.getTaskId())
                .eq(StudentGrade::getUserId, taskHistory.getUserId())
                .one();
        if (studentGrade == null) {
            studentGrade = new StudentGrade();
            studentGrade.setTaskId(taskHistory.getTaskId());
            studentGrade.setUserId(taskHistory.getUserId());
            studentGrade.setScore(taskHistory.getScore());
            studentGradeService.save(studentGrade);
        } else {
            if (studentGrade.getScore() < taskHistory.getScore()) {
                studentGrade.setScore(taskHistory.getScore());
                studentGradeService.updateById(studentGrade);
            }
        }
    }
}
